//
//  TabMineHistoryDeposit.swift
//  kz
//
//  Created by Tech_001 on 22/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import MJRefresh

class TabMineHistoryBonusController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    var _loadView: UIView?
    
    var requestPath: String?
    var requestType: String?
    
    var offset = 0
    var pageCount = 50
    var loadingData = false
    var noMoreData = false
    var firstQuery = false
    
    var rowHeight: CGFloat?
    var data: [[String:Any]]? = [[:]]
    var dataIndexOffset: Int {
        if self.requestType == HistoryType.order {
            return 4
        }else{
            return 2
        }
    }
    var gpData: [String:String]? = [:]
    
    var selectedMessage: [UIView:[String:String]]? = [:]
    
    let bottomLabelText: [String:[String]] = [
        HistoryType.bonus: [
            "金额",
            "",
            "单号"
        ],
        HistoryType.order: [
            "投注:",
            "输嬴:"
        ]
    ]
    let bottomLabelColumn: [String:[String]] = [
        HistoryType.bonus: [
            "gp",
            "time",
            "type",
            "",
            "money",
            "dno"
        ],
        HistoryType.order: [
            "gp_type",
            "bettime",
            "settleName",
            "betamt",
            "win"
        ],
    ]
    
    var valueTotal: CGFloat = 0.0
    var valueWin: CGFloat = 0.0

    var startControl: [String:UIControl]? = [:]
    var endControl: [String:UIControl]? = [:]
//    var buttonControl: [UIButton:[String:UIControl]] = [:]
    var datePickerControl: [UIDatePicker:[String:UIControl]] = [:]
    
    var gpPickerView: UIPickerView?
    var gpTextField: UITextField?
    var selectedGpIndex: Int = 0
    
    var initLoad = true
    
    let rc: MJRefreshHeader? = MJRefreshNormalHeader()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        
        rc!.setRefreshingTarget(self, refreshingAction: #selector(self.pullToRefresh))
        self.tableView.mj_header = rc
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        let topLogo = UIImage(named: "top_icon")
//        let ratio = topLogo!.size.height/topLogo!.size.width
//        let newWidth = UIHelper.fullSize.width * 0.4
//        let newHeight = newWidth * ratio
//        
//        let titleView = UIView()
//        let topLogoView = UIImageView(image: topLogo)
//        
//        titleView.addSubview(topLogoView)
//        topLogoView.contentMode = .scaleToFill
//        topLogoView.frame = CGRect(x: -(newWidth/2), y: -(newHeight/2), width: newWidth, height: newHeight)
//        
//        self.navigationItem.titleView = titleView
        self.rowHeight = tableView.rowHeight
        self.data?.removeAll()
        self.gpData?.removeAll()
        self.selectedMessage?.removeAll()
        
//        self.tableView.setNeedsLayout()
//        self.tableView.layoutIfNeeded()
        
        self.tableView.tableFooterView = UIView()
        
        let rightItem = UIBarButtonItem(title: "查询", style: .plain, target: self, action: #selector(self.pullToRefresh))
        self.navigationItem.rightBarButtonItem = rightItem
        self.navigationItem.title = self.requestType
        
        RequestHelper.get(atPath: "/clientsAPIs/getCodeList", withCompletion: { data in
            let responseArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
            self.gpData = responseArray
            
            DispatchQueue.main.async {
                self.gpPickerView?.reloadAllComponents()
            }
            
        }, withError: { error in
           
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "无法取得平台列表,\(getErrorString())", withDescription: "", in: self)
                self.gpData?.removeAll()
            }
        })
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.requestType == HistoryType.bonus {
            return data!.count + dataIndexOffset + 1
        } else {
            return data!.count + dataIndexOffset
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 46
        }else if indexPath.row == 1{
            return 46
        }else if indexPath.row == 2 && self.requestType == HistoryType.order{
            return 46
        }else if indexPath.row == 3 && self.requestType == HistoryType.order{
            return 46
        }else if indexPath.row == data!.count + dataIndexOffset {
            if firstQuery {
                return 44
            }
            return 0
        }else{
            if self.requestType == HistoryType.bonus {
                return self.rowHeight!
            }
            return 96
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == tableView.indexPathsForVisibleRows?.last?.row && initLoad {
            initLoad = false
            
            pullToRefresh()
        }
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "dateCell", for: indexPath) as! TabMineHistoryOrderDateTableViewCell
            
            cell.titleLabel?.text = "开始日期"
            
            if cell.textField.text!.count == 0 {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                
                let calendar = Calendar.current
                let date = calendar.date(byAdding: .day, value: -7, to: Date())
                
                cell.textField.text = dateFormatter.string(from: date!)
            }
            
            let controls = prepareDatePicker(cell)
            self.startControl = controls
            self.datePickerControl[controls["datePicker"] as! UIDatePicker] = controls
//            self.buttonControl[controls["button"] as! UIButton] = controls
            
            return cell
        }else if indexPath.row == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "dateCell", for: indexPath) as! TabMineHistoryOrderDateTableViewCell
            
            cell.titleLabel?.text = "结束日期"
            
            if cell.textField.text!.count == 0 {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                
                cell.textField.text = dateFormatter.string(from: Date())
            }
            
            let controls = prepareDatePicker(cell)
            self.endControl = controls
            self.datePickerControl[controls["datePicker"] as! UIDatePicker] = controls
//            self.buttonControl[controls["button"] as! UIButton] = controls
            
            return cell
        }else if indexPath.row == 2 && self.requestType == HistoryType.order{
            let cell = tableView.dequeueReusableCell(withIdentifier: "gpCell", for: indexPath) as! TabMineHistoryOrderGPViewCell
            let pickerView = preparePickerView(cell)
            pickerView.delegate = self
            pickerView.dataSource = self
            self.gpPickerView = pickerView
            self.gpTextField = cell.textField
      
            
            return cell
        }else if indexPath.row == 3 && self.requestType == HistoryType.order{
            let cell = tableView.dequeueReusableCell(withIdentifier: "summaryCell", for: indexPath) as! TabMineHistoryOrderSummaryViewCell

            cell.betLabel.text = String(format: "%.2f", self.valueTotal)
            cell.winLabel.text = String(format: "%.2f", self.valueWin)
            
            if self.valueWin >= 0 {
                cell.winLabel.textColor = UIColor.init(red: 0, green: 0.7, blue: 0, alpha: 1)
                cell.winLabel.text = "+" + cell.winLabel.text!
            } else {
                cell.winLabel.textColor = UIColor.init(red: 0.7, green: 0, blue: 0, alpha: 1)
            }
            
            return cell
        }else if indexPath.row == self.data!.count + dataIndexOffset && self.requestType == HistoryType.bonus{
            //Add loading view at the bottom
            let cell = tableView.dequeueReusableCell(withIdentifier: "loadingView", for: indexPath) as! TabMineHistoryNoDataTableCellView
            cell.layoutMargins = UIEdgeInsets.zero
            cell.indicator.startAnimating()
            
            //Hide loading view if no more data available
            if noMoreData {
                cell.noDataLabel.isHidden = false
            }else{
                cell.noDataLabel.isHidden = true
            }
            
            return cell
        }else{
            //Normal listing data
            let data = self.data![indexPath.row - dataIndexOffset]
            var cell: TabMineHistoryDepositTableViewCell
            if self.requestType == HistoryType.order {
                cell = tableView.dequeueReusableCell(withIdentifier: "orderCellNormal", for: indexPath) as! TabMineHistoryDepositTableViewCell
            }else{
                cell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath) as! TabMineHistoryDepositTableViewCell
            }
            
            cell.bottom1LeftLabel.text = bottomLabelText[requestType!]![0]
            cell.bottom2LeftLabel.text = bottomLabelText[requestType!]![1]
            
            cell.topLeftLabel.text = data[bottomLabelColumn[requestType!]![0]] as? String
            cell.topCenterLabel.text = data[bottomLabelColumn[requestType!]![1]] as? String
            cell.topRightLabel.text = data[bottomLabelColumn[requestType!]![2]] as? String
            cell.bottom1RightLabel.text = data[bottomLabelColumn[requestType!]![3]] as? String
            cell.bottom2RightLabel.text = data[bottomLabelColumn[requestType!]![4]] as? String
            if self.requestType == HistoryType.bonus {
                print(data)
                cell.middleLeftLabel.text = "\(bottomLabelText[requestType!]![2]): \(data[bottomLabelColumn[requestType!]![5]] as! String)"
                
            }
            
            if let win = (cell.bottom2RightLabel.text as NSString?)?.floatValue {
                if win >= 0 {
                    cell.bottom2RightLabel.text = "+" + cell.bottom2RightLabel.text!
                }
            }
            
            if self.requestType == HistoryType.bonus {
                if let superView = cell.bottom1LeftLabel.superview {
//                        if let parentStackView = superView.superview as? UIStackView{
//                            parentStackView.spacing = 0
//                        }
                    
                    cell.topRightLabel.textColor = UIColor.orange
                    cell.bottom2RightLabel.text = cell.bottom2RightLabel.text!
                    
                    if cell.bottom2RightLabel.text!.contains("-") {
                        cell.bottom2RightLabel.textColor = UIColor.init(red: 0.7, green: 0, blue: 0, alpha: 1)
                    } else {
                        cell.bottom2RightLabel.textColor = UIColor.init(red: 0, green: 0.7, blue: 0, alpha: 1)
                    }
                    
                    do{
                        if cell.topLeftLabel.text != "-" {
                            cell.topLeftLabel.text = try cell.topLeftLabel.text?.convertHtmlSymbols()
                        } else {
                            cell.topLeftLabel.text = "主账户"
                        }
                    } catch {
                        
                    }
                }
                //Add seperator line
                if UIHelper.fullSize.height >= ScreenSize.iPhone6.height {
                    let y = cell.frame.height/3 + 2
                    let view = UIView()
                    view.frame = CGRect(x: UIHelper.fullSize.width/2 - 0.75, y: y, width: 1.5, height: y)
                    view.backgroundColor = UIColor.groupTableViewBackground
                    
                    cell.contentView.addSubview(view)
                }
            } else {
                if (data["win"] as! String).contains("-") {
                    cell.bottom2RightLabel.textColor = UIColor.init(red: 0.7, green: 0, blue: 0, alpha: 1)
                }else{
                    cell.bottom2RightLabel.textColor = UIColor.init(red: 0, green: 0.7, blue: 0, alpha: 1)
                }
                
                do {
                    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.displayMessage(tapGestureRecognizer:)))
                    cell.contentView.isUserInteractionEnabled = true
                    cell.contentView.addGestureRecognizer(tapGestureRecognizer)
                    
                    let gp_type = try (data["gp_type"] as! String).convertHtmlSymbols()!
                    let bet_content = data["bet_content"] as! String
                    let bet_no = data["bet_no"] as! String
                    let betamt = data["betamt"] as! String
                    let win = data["win"] as! String
                    let settleName = try (data["settleName"] as! String).convertHtmlSymbols()!
                    let bettime = data["bettime"] as! String
                    let valid_amt = data["valid_amt"] as! String
                    let payout = data["payout"] as! String
                    
                    let message = [
                        "title": gp_type,
                        "content": "游戏：\(bet_content)\n单号：\(bet_no)\n下注：\(betamt)\n输嬴：\(win)\n状态：\(settleName)\n时间：\(bettime)\n流水：\(valid_amt)\n派彩：\(payout)\n",
                        "game" : bet_content,
                        "bet_no" : bet_no,
                        "betamt" : betamt,
                        "win" : win,
                        "settleName" : settleName,
                        "bettime" : bettime,
                        "valid_amt" : valid_amt,
                        "payout" : payout
                        
                    ]
                    print("\(message)")
                    self.selectedMessage?[cell.contentView] = message
                } catch {
                    
                }
            }
            return cell
        }
        
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if requestType == HistoryType.bonus && firstQuery == true{
            if !loadingData && !noMoreData && indexPath.row == data!.count {
                loadingData = true
                pullToRefresh(loadMore: true)
            }
        }
        
        if indexPath.row == self.data!.count + dataIndexOffset && self.requestType == HistoryType.bonus {
            cell.separatorInset = UIEdgeInsets(top: 0, left: self.view.bounds.width/2, bottom: 0, right: self.view.bounds.width/2)
        }
    }
    
    @objc func endEditing(_ sender: Any?){
        gpTextField?.endEditing(false)
        (startControl?["textField"] as! UITextField).endEditing(false)
        (endControl?["textField"] as! UITextField).endEditing(false)
        self.pullToRefresh(loadMore: true,useRC: true)
    }
    
    func preparePickerView(_ cell: TabMineHistoryOrderGPViewCell) -> UIPickerView {
        let view = UIView()
        
        let headerView = UIView()
        headerView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: 40.0)
        headerView.backgroundColor = UIColor.groupTableViewBackground
        
        let finishButton = UIButton()
        finishButton.setTitle("完成", for: .normal)
        finishButton.addTarget(self, action: #selector(self.endEditing(_:)), for: .touchUpInside)
        finishButton.setTitleColor(UIColor.init(red: 0.08, green: 0.49, blue: 0.98, alpha: 1), for: .normal)
        finishButton.frame = CGRect(x: cell.frame.width - 60, y: 0, width: 60.0, height: 40.0)
        
        let pickerView = UIPickerView()
        pickerView.frame = CGRect(x: 0, y: 44, width: cell.frame.width, height: pickerView.frame.height)
        
        headerView.addSubview(finishButton)
        view.addSubview(pickerView)
        view.addSubview(headerView)
        
        let viewHeight = headerView.frame.height + pickerView.frame.height
        view.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: viewHeight)
        
        UIHelper.addTopBorder(inView: headerView)
        
        cell.textField.inputView = view
        
        return pickerView
    }
    
    func prepareDatePicker(_ cell: TabMineHistoryOrderDateTableViewCell) -> [String:UIControl]{
        let view = UIView()
        
        let headerView = UIView()
        headerView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: 40.0)
        headerView.backgroundColor = UIColor.groupTableViewBackground
        
        let finishButton = UIButton()
        finishButton.setTitle("完成", for: .normal)
        finishButton.addTarget(self, action: #selector(self.handleDateChange(sender:)), for: .touchUpInside)
        finishButton.setTitleColor(UIColor.init(red: 0.08, green: 0.49, blue: 0.98, alpha: 1), for: .normal)
        finishButton.frame = CGRect(x: cell.frame.width - 60, y: 0, width: 60.0, height: 40.0)
        
        let datePickerView  : UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePicker.Mode.date
        datePickerView.addTarget(self, action:#selector(self.handleDateChange(sender:)), for: UIControl.Event.valueChanged)
        datePickerView.frame = CGRect(x: 0, y: 44, width: cell.frame.width, height: datePickerView.frame.height)
        
        headerView.addSubview(finishButton)
        view.addSubview(datePickerView)
        view.addSubview(headerView)
        
        let viewHeight = headerView.frame.height + datePickerView.frame.height
        view.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: viewHeight)
        
        UIHelper.addTopBorder(inView: headerView)
        
        cell.textField.inputView = view
        
        let returnData = [
            "datePicker": datePickerView,
            "textField": cell.textField,
            "button": finishButton
        ] as [String : UIControl]
        
        return returnData
    }
    
    @objc func handleDateChange(sender: UIControl) {
        if sender is UIButton {
            view.endEditing(true)
            return
        }
        
        if let controls = self.datePickerControl[sender as! UIDatePicker] {
            if let datePicker = controls["datePicker"] as? UIDatePicker {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                
                if let textField = controls["textField"] as? UITextField {
                    textField.text = dateFormatter.string(from: datePicker.date)
                  
                }
            }
        }
    }
    
    @objc func displayMessage(tapGestureRecognizer: UITapGestureRecognizer){
        if let view = tapGestureRecognizer.view {
            if let message = self.selectedMessage?[view] {
                PopWindowHelper.showBettingRecordPopView(title: message["title"] as! NSString, msg: message)
               // UIHelper.alertSimpleMessagemt(about: message["title"]!, withDescription: message["content"]!, in: self, withOKButton: true)
            }
        }
    }
    
    func pullToRefreshRC(){
        self.pullToRefresh(loadMore: false, useRC: true)
    }
    
    @objc func pullToRefresh(loadMore: Bool = false, useRC: Bool = false){
        firstQuery = true
        if loadMore == false {
            self.offset = 0
            noMoreData = false
            loadingData = true
            
            if useRC == false {
                self.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: false)
                self._loadView = UIHelper.initLoadView(self, withMessage: "获取中...")
                self.tabBarController?.view.addSubview(self._loadView!)
                self.tableView.setContentOffset(CGPoint(x: 0, y: -64), animated: false)
            }
        }
        
        
        
        let startDateString: String
        let endDateString: String
        
        if startControl?["datePicker"] != nil && endControl?["datePicker"] != nil {
            let startTextField = startControl?["textField"] as? UITextField
            let endTextField = endControl?["textField"] as? UITextField
            
            if startTextField != nil && endTextField != nil {
                startDateString = startTextField!.text!
                endDateString = endTextField!.text!
            }else{
                return
            }
        }else{
            return
        }
        
        var gpId: String = "0"
        if selectedGpIndex != 0 {
            gpId = Array(gpData!.keys)[selectedGpIndex - 1]
        }
        
        var params = [
            "start": startDateString + " 00:00:00",
            "end": endDateString + " 23:59:59",
            "gpId": gpId
        ]
        
        if self.requestType == HistoryType.bonus {
            params["pageCount"] = "\(self.pageCount)"
            params["offset"] = "\(self.offset)"
        }
        
        let paramString = RequestHelper.convertGetParams(params)
        RequestHelper.get(atPath: self.requestPath! + "?\(paramString)", withCompletion: { data in
            do{
                let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
                var numToAdd = dataArray.count
                
                DispatchQueue.main.async {
                    if self.requestType == HistoryType.bonus {
                        if numToAdd > 0 {
                            if (loadMore == false) {
                                self.data!.removeAll()
                                self.selectedMessage!.removeAll()
                            }
                            for entry in dataArray {
                                self.data!.append(entry)
                            }
                            self.offset += numToAdd
                            self.tableView.reloadData()
                        }else{
                            if (loadMore == false) {
                                self.data?.removeAll()
                                self.calculateTotalAndWin()
                                self.tableView?.reloadData()
                                
                                self.rc?.endRefreshing()
                                UIHelper.alertSimpleMessage(about: "当前时间内没有任何记录，请更改条件", withDescription: "", in: self)
                            }
                            
                            self.noMoreData = true
                            self.tableView.reloadData()
                        }
                        
                        self.loadingData = false
                    } else {
                        if numToAdd != 0 {
                            self.data = dataArray
                            self.calculateTotalAndWin()
                            self.tableView?.reloadData()
                        } else {
                            self.data?.removeAll()
                            self.calculateTotalAndWin()
                            self.tableView?.reloadData()
                            
                            self.rc?.endRefreshing()
                            UIHelper.alertSimpleMessage(about: "当前时间内没有任何记录，请更改条件", withDescription: "", in: self)
                        }
                    }
                    
                    self.rc?.endRefreshing()
                    self._loadView?.removeFromSuperview()
                }
            } catch {
                DispatchQueue.main.async {
                    self.rc?.endRefreshing()
                    self._loadView?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生错误,\(getErrorString())", in: self)
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                self.rc?.endRefreshing()
                self._loadView?.removeFromSuperview()
                UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生错误,\(getErrorString())", in: self)
            }
        })
    }
    
    func calculateTotalAndWin() {
        self.valueTotal = 0
        self.valueWin = 0
        
        for data in self.data! {
            if let winString = data["win"] as? String {
                let win = CGFloat((winString as NSString).floatValue)
                let amountString = data["betamt"] as! String
                
                self.valueWin += win
                self.valueTotal += CGFloat((amountString as NSString).floatValue)
            }
        }
    }
    
    /**** PickerView ****/
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return gpData!.count + 1
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if row == 0 {
            return "全平台"
        }else {
            return Array(gpData!.values)[row-1]
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if row == 0 {
            gpTextField?.text = "全平台"
        }else {
            let values = Array(gpData!.values)
            gpTextField?.text = values[row - 1]
        }
        selectedGpIndex = row
    }
}
